package com.xizi.forum.service.impl;

import com.xizi.forum.common.AppResult;
import com.xizi.forum.common.ResultCode;
import com.xizi.forum.dao.ArticleInfoMapper;
import com.xizi.forum.exception.ApplicationException;
import com.xizi.forum.model.ArticleInfo;
import com.xizi.forum.service.IArticleInfoService;
import com.xizi.forum.service.IBoardInfoService;
import com.xizi.forum.service.IUserService;
import com.xizi.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

@Service
@Slf4j
public class ArticleInfoServiceImpl implements IArticleInfoService {
    @Autowired
    private ArticleInfoMapper articleInfoMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBoardInfoService boardInfoService;


    @Override
    public AppResult insertArticle(ArticleInfo articleInfo) {
        //查看板块id 是否 有效 后续补充

        if(StringUtil.isEmpty(articleInfo.getTitle()) || StringUtil.isEmpty(articleInfo.getContent())){
            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //  新增帖子
        int articleInfoCount = articleInfoMapper.insertSelective(articleInfo);

        long userId = articleInfo.getUserId();
        long boardId = articleInfo.getBoardId();
        // 改变用户发布帖子的数量
        int userInfoUpdateCount = userService.updateUserArticleCount(userId,true);
        // 改变 板块帖子 帖子数量
        int boardInfoUpdateCount = boardInfoService.updateBoardArticleCount(boardId,true);

        log.info( "userId: {} ,boardId: {}" , userId,boardId);

        if(articleInfoCount != 1 || userInfoUpdateCount != 1 || boardInfoUpdateCount != 1){
            log.info("为满足条件，手动回滚事务！");
            log.info("articleInfoCount: {} , userInfoUpdateCount : {} , boardInfoUpdateCount : {}",
                    articleInfoCount, userInfoUpdateCount,boardInfoUpdateCount);

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AppResult.fail(ResultCode.FAILED_CREATE);
        }

        log.info("新增帖子成功！");
        return AppResult.success();

    }

    /**
     * 获取当前版块下的所有帖子
     * @param boardId 版块id
     * @return
     */
    @Override
    public List<ArticleInfo> selectAllArticleByBoardId(Long boardId) {
        //1.参数校验
        if(boardId == null || boardId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        List<ArticleInfo> articleInfos = articleInfoMapper.selectAllArticleByBoardId(boardId);
        return articleInfos;
    }

    /**
     * 获取所有帖子
     * @return
     */
    @Override
    public List<ArticleInfo> selectAllArticle() {
        List<ArticleInfo> articleInfos =  articleInfoMapper.selectAllArticle();
        return articleInfos;
    }

    /**
     * 获取帖子详情
     * @param id 帖子id
     * @return
     */
    @Override
    public ArticleInfo selectArticleById(Long id) {
        // 参赛校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //1.帖子浏览量加 1
        ArticleInfo articleInfo = articleInfoMapper.selectByPrimaryKey(id);
        ArticleInfo updateArticleInfo = new ArticleInfo();
        updateArticleInfo.setId(id);
        updateArticleInfo.setVisitCount(articleInfo.getVisitCount() + 1);
        int i = articleInfoMapper.updateByPrimaryKeySelective(updateArticleInfo);
        if(i != 1){
            log.error("修改数量不为一，出错了");
            throw new ApplicationException(ResultCode.FAILED_CREATE);
        }
        // 2. 查询帖子 详情信息
        ArticleInfo articleInfoDetail = articleInfoMapper.selectDetailsById(id);

        return articleInfoDetail;
    }

    /**
     * 修改帖子
     * @param articleInfo 帖子对象
     * @return
     */
    @Override
    public Boolean updateArticleById(ArticleInfo articleInfo) {
        //1.参数校验
        if(articleInfo.getId() == null || articleInfo.getId() < 0 ||
                StringUtil.isEmpty(articleInfo.getTitle()) || StringUtil.isEmpty(articleInfo.getContent())){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        int i = articleInfoMapper.updateByPrimaryKeySelective(articleInfo);
        // sql 校验
        if(i == 1) return true;

        throw new ApplicationException(ResultCode.FAILED);
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @Override
    public Boolean updateLike(Long id) {
        //1.参数校验
        if(id == null || id < 0){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.校验帖子情况
        ArticleInfo articleInfo = articleInfoMapper.selectByPrimaryKey(id);
        if(articleInfo == null || articleInfo.getDeleteState() == 1){
            log.error(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_NOT_EXISTS);
        }

        ArticleInfo updateArticleInfo = new ArticleInfo();
        updateArticleInfo.setId(id);
        updateArticleInfo.setLikeCount(articleInfo.getLikeCount() + 1);
        int i = articleInfoMapper.updateByPrimaryKeySelective(updateArticleInfo);
        log.info("点赞操作, 修改条数:" + i + ",id = " + id);

        if(i != 1) throw new ApplicationException(ResultCode.FAILED);
        return true;
    }

    /**
     * 删除帖子
     * @param id 帖子id
     * @return
     */
    @Override
    public Boolean deleteArticle(Long id) {
        //1. 参数校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.校验帖子状态
        ArticleInfo articleInfo = articleInfoMapper.selectByPrimaryKey(id);
        if(articleInfo == null || articleInfo.getDeleteState() == 1){
            throw new ApplicationException(ResultCode.FAILED_NOT_EXISTS);
        }

        //1. 这个帖子的作者发布帖子数 减 1
        Long userId = articleInfo.getUserId();
        int userCount = userService.updateUserArticleCount(userId,false);
        //2.帖子所属的板块，帖子数 减 1
        Long boardId = articleInfo.getBoardId();
        int boardCount = boardInfoService.updateBoardArticleCount(boardId,false);
        //3.当前帖子状态 修改为 删除状态
        articleInfo.setDeleteState((byte) 1);
        int articleCount = articleInfoMapper.updateByPrimaryKeySelective(articleInfo);
        //4.校验sql
        if(articleCount != 1 || userCount != 1 || boardCount != 1){
            throw new ApplicationException(ResultCode.FAILED);
        }

        return true;
    }

    /**
     * 通过用户id 获取 用户发布的所有帖子
     * @param userId 用户id
     * @return
     */
    @Override
    public List<ArticleInfo> getAllByUserId(Long userId) {
        //1.校验参数
        if(userId == null || userId <= 0){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        List<ArticleInfo> list = articleInfoMapper.selectAllByUserId(userId);
        return list;
    }
}
